import { ElLoading } from "element-plus";
import { confirm, error, success, warning } from "../utils/message";
import { download, getRequest, permissionResources, postRequest } from "./star_horse";
import { useRouter } from "vue-router";
import { getToken, getUserInfo } from "@/utils/auth";
import Speech from "speak-tts";

export const common = {
  
    data() {
        const router = useRouter();
        const speech = new Speech();
        speech.setLanguage("zh-CN");
        speech.init().then(() => {
            console.log("语音播报初始化完成");
        });
        
        return {
            speech,
            count: 1,
            loading: null,
            batchDialogTitle: "",
            props: { label: "areaName", value: "areaCode" },
            labelPosition: "right",
            batchDialogTableVisible: false,
            dialogTableVisible: false,
            uploadVisible: false,
            viewVisible: false,
            readonly:false,
            dialogTitle: "",
            ruleForm: { batchDataList: [] },
            searchForm: {},
            uploadData: { "ruleForm": this.ruleForm },
            dataList: [],
            permission: { view: "view" },
            checkedDetail: [],
            departList: [],
            educations: [],
            politicals: [],
            credentials: [],
            rolesList: [],
            selectData: [],
            areaList: [],
            fileList:[],
            uploadHeaders: {
                token: getToken()
            },
            userInfo: getUserInfo(),
            currentPage: 1,
            pageSize: 20,
            totalPage: 0,
            totalData: 0,
            dialogImageUrl: '',
            rules: {},
            isUpload: false,
            isFullScreen: false,
            webSocket: null,
            webSocketId: null,
            currentIp: null,
            openSpeak: true,
            router,
            loadTarget: "#app"
        }
    },
    methods: {

        playMessage(msg, recall) {
            let _this = this;
            if (!_this.openSpeak) {
                return;
            }
            if (!msg) {
                if (recall) {
                    recall();
                }
                return;
            }
            _this.speech.speak({ text: msg }).then(() => {
                if (recall) {
                    recall();
                }
            });
        },

        handleAddDetails(row, type) {
            if (type === 1) {
                let obj = {};
                this.ruleForm["batchDataList"].push(obj);
            } else {
                this.ruleForm["batchDataList"].splice(row.xh - 1, 1);
            }
        },
        /**
         * 加载框
         */
        load(msg) {
            let _this = this;
            _this.closeLoad();
            _this.loading = ElLoading.service({
                    lock: true,
                    target: _this.loadTarget,
                    text: msg || 'Loading...',
                    background: 'rgba(0, 0, 0, 0.7)',
                });
        },
        closeLoad() {
            if (this.loading) {
                this.loading.close();
                this.loading = null;
            }
        },
        addDataFun() {
            this.resetForm();
            this.readonly=false;
            this.dialogTableVisible = !this.dialogTableVisible;
            this.dialogTitle = "新增数据";
        },
        batchAddDataFun() {
            this.resetForm();
            this.readonly=false;
            this.batchDialogTableVisible = !this.batchDialogTableVisible;
            this.dialogTitle = "批量新增";
        },
        /**
         * 按钮操作
         */
        btnOperation(type) {
            let _this=this;
            _this.closeLoad();
            if(!type){
                return;
            }
            let arr={
                1:"addDataFun",
                4:"delete",
                5:"refresh",
                6:"downloadTemplate",
                8:"exportAll",
                11:"batchAddDataFun"
            }
            let funs=_this.$options.methods;
            if(typeof type=='number'){
                type=arr[type];
            }
            let fun=funs[type];
            fun.call(_this);
        },

        editById(id) {
            this.resetForm();
            this.readonly=true;
            this.dialogTitle = "编辑数据";
            this.loadById(id);
        },
        viewById(id) {
            this.loadById(id, true);
        },
        handleDeleteById(dUrl, id) {
            let _this = this;
            confirm("确认需要删除选择的数据吗？", function (ok) {
                if (!ok) {
                    return;
                }
                _this.load();
                getRequest(`${dUrl}/${id}`).then(res => {
                    success(res.data.cnMessage);
                    _this.multipleSelection = [];
                    _this.closeLoad();
                    _this.loadByPage(_this.currentPage, _this.pageSize);
                }).catch(err => {
                    error("接口不存在或网络异常:" + err)
                }).finally(() => {
                    _this.closeLoad();
                })
            });
        },
        handlePostDeleteById(dUrl, id) {
            let _this = this;
            confirm("确认需要删除选择的数据吗？", function (ok) {
                if (!ok) {
                    return;
                }
                _this.load();
                postRequest(`${dUrl}/${id}`).then(res => {
                    success(res.data.cnMessage);
                    _this.multipleSelection = [];
                    _this.closeLoad();
                    _this.loadByPage(_this.currentPage, _this.pageSize);
                }).catch(err => {
                    error("接口不存在或网络异常:" + err)
                }).finally(() => {
                    _this.closeLoad();
                })
            });
        },
        deleteById(id) {
            this.doDelete([id]);
        },
        handleDeleteDetails() {
            if (this.checkedDetail.length == 0) {
                warning("请先选择要删除的数据");
            } else {
                this.batchDataList.splice(this.checkedDetail[0].xh - 1, 1);
            }
        },
        handleDeleteAllDetails() {
            this.ruleForm["batchDataList"] = [];
        },
        getRowIdentity(row) {

            return row[this.primaryKey];
        }
        ,

        pageClick(type) {
            this.loadByPage(this.currentPage, this.pageSize);
        }
        ,
        pageSizeClick(pageSize) {
            this.pageSize = pageSize;
            this.loadByPage(this.currentPage, pageSize);
        }
        ,
        pageChangeClick(currentPage) {
            this.currentPage = currentPage;
            this.loadByPage(this.currentPage, this.pageSize);
        }
        ,
        editData(row, column, event) {
            this.loadById(row[this.primaryKey], true);
        }
        ,
        //重置数据
        resetForm() {
            this.ruleForm = {};
            this.ruleForm["batchDataList"] = [{}];
        }
        ,
        //处理选中的数据
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        /**
         * 加载资源权限
         */
        loadPermissionResources() {
            let _this = this;
            let meta = _this.$router.currentRoute.value.meta;
            let data = { "menuId": meta.menuId };
            //
            if (meta.menuId == 14) {
                return;
            }
            permissionResources(data).then(res => {
                let redata = res.data.data;
                redata.forEach(item => {
                    _this.permission[item.resCode] = item.resCode;
                });
            });
        },
        /**
         * 获取已选中数据的Id
         */
        getSelectedData() {
            let ids = [];
            if (!this.multipleSelection) {
                return ids;
            }
            this.multipleSelection.forEach(item => ids.push(item[this.primaryKey]));
            return ids;
        },
        removeOne() {
            this.isUpload = false;
            setTimeout(function () {
                document.getElementsByClassName("el-upload")[0].style.display = ""
            }, 500)

        },
        imageOne(file) {
            this.isUpload = true;
            document.getElementsByClassName("el-upload")[0].style.display = "none"
        },

        /**
         * 状态码数据
         */
        commonSelectData(type, callFun) {
            let _this = this;
            let query = [];
            query.push({
                "propertyName": "statusType",
                "value": type
            })
            postRequest("/system-config/system/statusinfoEntity/getAllByCondition", query).then(res => {
                let redata = res.data;
                if (callFun) {
                    callFun(redata.data);
                } else {
                    _this.selectData = redata.data;
                }
            }).catch(err => {
                error("接口不存在或网络异常");
            });
        },
        /**
         * 上传数据
         */
        upload(file, fileList) {
        this.fileList=fileList;
        },
        /**
         * 上传过程
         */
        uploadProcess(event, file, fileList) {
            this.load("数据导入中,请等待");
        },
        /**
         * 上传失败
         */
        uploadError(err, file, fileList) {
            error(err.message);
            this.closeLoad();
        },
        /**
         * 上传成功
         */
        uploadSuccess(response, file, fileList) {
            if (response.code == 1) {
                error(response.cnMessage)
            } else {
                success(response.cnMessage);
            }

            this.closeLoad();
            // this.$refs.userUpload.clearFiles();
            // this.dialogTableVisible = !this.dialogTableVisible;
            this.refresh();
        },
        /**
         * 刷新数据
         */
        refresh: function () {
            this.init();
        },
        beforeUpload(file) {
            return !!file;
        },
        rowClassName({ row, rowIndex }) {
            row.xh = rowIndex + 1;
        },
        //单选框选中数据
        handleDetailSelectionChange(selection) {
            if (selection.length > 1) {
                this.$refs.tb.clearSelection();
                this.$refs.tb.toggleRowSelection(selection.pop());
            } else {
                this.checkedDetail = selection;
            }
        },
        dataSearch: function (type) {
            if (type == 1) {
                this.searchForm = {};
            }
            this.loadByPage(this.currentPage, this.pageSize);
        },
        parseSearchData() {
            return [];
        },
        commonDataFormat(row, column, cellValue, index) {
           return this.commonParseCodeToName(column.property,cellValue);
        },

        commonParseCodeToName(name, cellValue) {
            if (!cellValue) {
                return "-";
            }
            if (name == "isDel") {
                return cellValue == 1 ? "是" : "否";
            }
            if (name == "state") {
                return cellValue == 1 ? "正常" : "异常";
            }
            let preps = ["createdTime", "updatedTime", "createdDate", "updatedDate"];
            let result = preps.find(item => name.toLowerCase() === item.toLowerCase());
            if (result) {
                return this.createDatetime(cellValue);
            } else {
                return cellValue;
            }
        },
        /**
         * 创建日期
         * @param val
         * @returns {string}
         */
        createDate(val) {
            if (!val) {
                return "--";
            }
            let date = new Date(val);
            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
        },
        /** custom  */
        createFormatDate(format, val) {
            if (!val) {
                return;
            }
            let date = new Date(val);
            let o = {
                "M+": date.getMonth() + 1, //月份         
                "d+": date.getDate(), //日         
                "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时         
                "H+": date.getHours(), //小时         
                "m+": date.getMinutes(), //分         
                "s+": date.getSeconds(), //秒         
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度         
                "S": date.getMilliseconds() //毫秒         
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (let k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return format;
        },
        createDatetime(val) {
            if (!val || val == "undefined" || val == "-") {
                return "--";
            }
            let date = new Date(val);
            let hour=date.getHours()<10?'0'+date.getHours():date.getHours();
            let minute=date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + hour + ":" + minute;
        },
        /**
         * 对状态名称赋值
         */
        assignStatusName: function () {
            let _this = this;
            if (_this.ruleForm.statusCode) {
                let sData = _this.selectData.find(item => item.statusCode === _this.ruleForm.statusCode);
                if (sData) {
                    _this.ruleForm["statusName"] = sData.statusName;
                }
            }
            if (_this.ruleForm.batchDataList) {
                for (let index = 0; index < _this.ruleForm.batchDataList.length; index++) {
                    let temp = _this.ruleForm.batchDataList[index];
                    let sData = _this.selectData.find(item => item.statusCode === temp.statusCode);
                    if (sData && sData.statusName) {
                        _this.ruleForm.batchDataList[index]["statusName"] = sData.statusName;
                    }
                }
            }

        },
        /**
         * 分页显示数据
         */
        loadByPage: function (currentPage, pageSize) {
            let _this = this;
            _this.load();
            postRequest(_this.loadByPageUrl, {
                currentPage: currentPage < 1 ? 1 : currentPage,
                pageSize: pageSize || _this.pageSize,
                fieldList: _this.parseSearchData()
            }).then(res => {
                let redata = res.data.data;
                _this.dataList = redata.dataList;
                _this.totalPage = redata.totalPages;
                _this.currentPage = currentPage < 1 ? 1 : currentPage;
                _this.totalData = redata.totalDatas;
            }).catch(err => {
                error("接口不存在或网络异常:"+err);
            }).finally(() => {
                _this.closeLoad();
            })
        },
        /**
         * 获取表单引用
         * @returns 
         */
        getMergeRef(isBatch,callFun){
            let _this=this;
            //兼容旧的引用
            let ref= _this.$refs["ruleForm"];
            let batchRefName="mergeDataFormBatchRef";
            let formRef="starHorseFormRef";
            let fRef=isBatch?batchRefName:"mergeDataFormRef";
            //如果存在旧的引用则返回旧的，否则返回新的引用
            ref= ref ||_this.$refs[fRef]?.$refs[formRef];
           ref.validate((valid)=>{
            //如果存在子组件列表Form
               let sref= _this.$refs[fRef]?.$refs[batchRefName]?.$refs[formRef];
               if(sref){
                sref.validate((svalid)=>{ callFun(valid&&svalid)});
               }else{
                callFun(valid);
               }
             
            });
        },
        /**
         * 编辑保存数据
         */
        merge(isBatch) {
            if (isBatch) {
                this.batchMerge();
                return;
            }
            let _this = this;
            _this.getMergeRef(false,(valid)=>{
                if (!valid) {
                    return;
                }
                _this.assignStatusName();
                _this.load();
                if (this.isUpload) {
                    this.$refs.userUpload.submit();
                    this.removeOne();
                    _this.closeLoad();
                } else {
                    postRequest(_this.mergeUrl, _this.ruleForm).then(res => {
                        _this.closeLoad();
                        if (res.data.code == 1) {
                            warning(res.data.cnMessage);
                            return;
                        } else {
                            success(res.data.cnMessage);
                        }
                        _this.loadByPage(1, _this.pageSize);
                        _this.ruleForm = {};
                        _this.dialogTableVisible = !_this.dialogTableVisible;
                    }).catch(err => {
                        error("接口调用异常" + err);
                    }).finally(() => {
                        _this.closeLoad();
                    })
                }
            });
        },
        /**
         * 编辑保存数据
         */
        mergeDraft(isBatch) {
            if (isBatch) {
                this.batchMergeDraft();
                return;
            }
            let _this = this;
            _this.assignStatusName();
            _this.load();
            postRequest(_this.mergeDraftUrl, _this.ruleForm).then(res => {
                _this.closeLoad();
                if (res.data.code == 1) {
                    warning(res.data.cnMessage);
                    return;
                } else {
                    success(res.data.cnMessage);
                }
                _this.loadByPage(1, this.pageSize);
                _this.resetForm();
                _this.dialogTableVisible = !_this.dialogTableVisible;
            }).catch(err => {
                error("接口不存在或网络异常");
            }).finally(() => {
                _this.closeLoad();
            })
        }
        ,
        /**
         * 批量编辑保存数据
         */
        batchMerge: function () {
            let _this = this;
            _this.getMergeRef(true,(valid)=>{
                if (!valid) {
                    return;
                }
                _this.assignStatusName();
                _this.load();
                postRequest(_this.batchMergeUrl, _this.ruleForm.batchDataList).then(res => {
                    _this.closeLoad();
                    if (res.data.code == 1) {
                        warning(res.data.cnMessage);
                        return;
                    } else {
                        success(res.data.cnMessage);
                    }
                    _this.loadByPage(1, _this.pageSize);
                    _this.resetForm();
                    _this.batchDialogTableVisible = !_this.batchDialogTableVisible;
                }).catch(err => {
                    error("接口不存在或网络异常");
                }).finally(() => {
                    _this.closeLoad();
                })
            });
        },
        /**
         * 批量编辑保存草稿数据
         */
        batchMergeDraft: function () {
            let _this = this;
            _this.assignStatusName();
            _this.load();
            postRequest(_this.batchMergeDraftUrl, _this.batchDataList).then(res => {
                _this.closeLoad();
                if (res.data.code == 1) {
                    warning(res.data.cnMessage);
                    return;
                } else {
                    success(res.data.cnMessage);
                }
                _this.loadByPage(1, _this.pageSize);
                _this.resetForm();
                _this.batchDialogTableVisible = !_this.batchDialogTableVisible;
            }).catch(err => {
                error("接口不存在或网络异常");
            }).finally(() => {
                _this.closeLoad();
            })
        },

        /**
         * 加载指定数据
         */
        loadById(id, isView) {
            let _this = this;
            _this.load();
            getRequest(_this.loadByIdUrl + (isView ? "ForView" : "") + "/" + id).then(res => {
                let redata = res.data.data;
                if (!redata) {
                    warning("未找到对应数据");
                    return;
                }
                _this.ruleForm = redata;
                if(!this.ruleForm["batchDataList"]||this.ruleForm["batchDataList"].length==0){
                    _this.ruleForm["batchDataList"]=[{}];
                }

                if (isView && isView != 3) {
                    this.viewVisible = !this.viewVisible;
                } else {
                    if (isView == 3) {
                        this.dialogPwdVisible = !this.dialogPwdVisible;
                    } else {

                        this.dialogTableVisible = !this.dialogTableVisible;
                    }
                }
                if (_this.ruleForm.nativePlace) {
                    _this.ruleForm.nativePlace = _this.ruleForm.nativePlace.split(",");
                }

            }).catch(err => {
                error("接口不存在或网络异常");
            }).finally(() => {
                _this.closeLoad();
            })
        },
        /**
         * 删除数据
         */
        delete() {
            let _this = this;
            if (!_this.multipleSelection || _this.multipleSelection.length == 0) {
                warning("请选择要删除的数据");
                return;
            }
            _this.doDelete(_this.getSelectedData());
        },
        doDelete(data) {
            let _this = this;
            confirm("确认需要删除选择的数据吗？", function (ok) {
                if (!ok) {
                    return;
                }
                _this.load();
                postRequest(_this.deleteUrl, data).then(res => {
                    success(res.data.cnMessage);
                    _this.multipleSelection = [];
                    _this.closeLoad();
                    _this.loadByPage(_this.currentPage, _this.pageSize);
                }).catch(err => {
                    error("接口不存在或网络异常:" + err)
                }).finally(() => {
                    _this.closeLoad();
                })
            });
        },

        /**
         * 导出所有数据
         */
        exportAll() {
            let _this = this;
            /* if (!_this.getSelectedData().join()) {
                 return error('请选择数据进行导出')
             }*/
            _this.load();
            download(this.exportAllUrl, _this.getSelectedData()).catch(err => {
                error("接口不存在或网络异常:" + err);
            }).finally(() => {
                _this.closeLoad();
            })
        },
        /**
         * 下载模板
         */
        downloadTemplate() {
            let _this = this;
            download(this.downloadTemplateUrl, {}).catch(err => {
                error("接口不存在或网络异常:" + err);
            });
        },
        /**
         * 初始化Websocket
         */
        initWebSocket(ip, webSocketId) {
            if (!ip) {
                warning("请提供WebSocket地址");
                return;
            }
            if (!webSocketId) {
                warning("请提供WebSocketID");
                return;
            }
            let _this = this;
            _this.webSocketId = webSocketId;
            _this.currentIp = ip;
            if ('WebSocket' in window) {
                _this.webSocket = new WebSocket("ws://" + ip + "/websocket/socketHandler?moduleName=" + webSocketId + "&token=" + getToken());
            } else if ('MozWebSocket' in window) {
                _this.webSocket = new MozWebSocket("ws://" + ip + "/websocket/socketHandler?moduleName=" + webSocketId + "&token=" + getToken());
            } else {
                _this.webSocket = new SockJs(ip + "/websocket/socketHandler?moduleName=" + webSocketId + "&token=" + getToken());
            }
            _this.webSocket.onopen = _this.websocketOpen;
            _this.webSocket.onerror = _this.websocketError;
            _this.webSocket.onmessage = _this.websocketMessage;
            _this.webSocket.onclose = _this.websocketClose;
        },
        webSocketSendData(data) {
            let _this = this;
            _this.webSocket.send(data);
        },
        websocketOpen() {
            let _this = this;
            _this.webSocketSendData(_this.webSocketId);
        },
        websocketError(e) {
            console.error("连接Websocket 异常", e);
        },
        websocketMessage(msg) {
            let _this = this;
            let data = msg.data;
            if (data) {
                let jsonData = JSON.parse(data);
                if (parseInt(jsonData.code) === 2) {
                    _this.loadByPage(1, _this.pageSize);
                }
            }
            //获取消息后重新拉取一次数据

        },
        websocketClose(e) {
            // console.log("webSocket 断开链接", e);
            this.reconn();
        },
        reconn() {
            let _this = this;
            setTimeout(function () {
                _this.initWebSocket(_this.currentIp, _this.webSocketId);
            }, 1000);
        }
    }
}